import kurentoUtils from "kurento-utils";
let webRtcPeer;
let response;
let callerMessage;
let from;

let registerName = null;

/**
 * 设置常量 用判断是否注册过websocket
 */

const NOT_REGISTERED = 0;
const REGISTERING = 1;
const REGISTERED = 2;

/**
 * 设置常量 用判断是否Call
 */
const NO_CALL = 0;
const PROCESSING_CALL = 1;
const IN_CALL = 2;

export let videoInput = null;
export let videoOutput = null;
export let registerState = null;
export let callState = null;
// 创建和后台的Websocket连接
// console.log("zyd");
export let ws = null;

export function setVedio(input, output) {
  videoInput = input;
  videoOutput = output;
}
// websocket 根据注册状态设置Call状态以及按钮状态
function setRegisterState(nextState) {
  switch (nextState) {
    case NOT_REGISTERED:
      setCallState(NO_CALL);
      break;
    case REGISTERING:
      break;
    case REGISTERED:
      setCallState(NO_CALL);
      break;
    default:
      return;
  }

  registerState = nextState;
}

// 设置按钮状态
function setCallState(nextState) {
  switch (nextState) {
    case NO_CALL:
      // enableButton("#call", "call()");
      // disableButton("#terminate");
      // disableButton("#play");
      break;
    case PROCESSING_CALL:
      // disableButton("#call");
      // disableButton("#terminate");
      // disableButton("#play");
      break;
    case IN_CALL:
      // disableButton("#call");
      // enableButton("#terminate", "stop()");
      // disableButton("#play");
      break;
    default:
      return;
  }
  callState = nextState;
}

export function init() {
  // 打印消息
  console.log("初始化");
  ws = new WebSocket("wss://192.168.0.15:8443/call");
  ws.onmessage = function(message) {
    let parsedMessage = JSON.parse(message.data);
    console.info("Received message: " + message.data);

    switch (parsedMessage.id) {
      case "resgisterResponse":
        resgisterResponse(parsedMessage);
        break;
      case "callResponse":
        callResponse(parsedMessage);
        break;
      case "incomingCall":
        incomingCall(parsedMessage);
        break;
      case "startCommunication":
        startCommunication(parsedMessage);
        break;
      case "stopCommunication":
        console.info("Communication ended by remote peer");
        stop(true);
        break;
      case "iceCandidate":
        webRtcPeer.addIceCandidate(parsedMessage.candidate, function(error) {
          if (error) return console.error("Error adding candidate: " + error);
        });
        break;
      case "getRoomMessage":
        getRoomMessage(parsedMessage);
        break;
      case "getOnlineUsersRes":
        getOnlineUsersRes(parsedMessage);
        break;
      default:
        console.error("Unrecognized message", parsedMessage);
    }
  };
}

export function destory() {
  console.log("关闭");
  ws.close();
}

// 注册响应
function resgisterResponse(message) {
  if (message.response == "accepted") {
    setRegisterState(REGISTERED);
  } else {
    setRegisterState(NOT_REGISTERED);
    let errorMessage = message.message
      ? message.message
      : "Unknown reason for register rejection.";
    console.log(errorMessage);
    alert("Error registering user. See console for further information.");
  }
}

// 调用响应
function callResponse(message) {
  if (message.response != "accepted") {
    console.info("Call not accepted by peer. Closing call");
    let errorMessage = message.message
      ? message.message
      : "Unknown reason for call rejection.";
    console.log(errorMessage);
    stop();
  } else {
    setCallState(IN_CALL);
    webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
      if (error) return console.error(error);
    });
  }
}

function incomingCall(message) {
  // If bussy just reject without disturbing user
  if (callState != NO_CALL) {
    let response = {
      id: "incomingCallResponse",
      from: message.from,
      callResponse: "reject",
      message: "bussy"
    };
    return sendMessage(response);
  }

  setCallState(PROCESSING_CALL);
  if (
    window.confirm(
      "User " + message.from + " is calling you. Do you accept the call?"
    )
  ) {
    from = message.from;
    let iceservers = {
      iceServers: [
        {
          urls: "stun:192.168.0.15:3478"
        },
        {
          urls: ["turn:192.168.0.15:3478"],
          username: "kurento",
          credential: "kurento"
        }
      ]
    };
    let options = {
      localVideo: videoInput,
      remoteVideo: videoOutput,
      configuration: iceservers,
      onicecandidate: onIceCandidate,
      onerror: onError
    };
    webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(
      options,
      function(error) {
        if (error) {
          return console.error(error);
        }
        webRtcPeer.generateOffer(onOfferIncomingCall);
      }
    );
  } else {
    let response = {
      id: "incomingCallResponse",
      from: message.from,
      callResponse: "reject",
      message: "user declined"
    };
    sendMessage(response);
    stop();
  }
}

function startCommunication(message) {
  setCallState(IN_CALL);
  webRtcPeer.processAnswer(message.sdpAnswer, function(error) {
    if (error) return console.error(error);
  });
}

function onOfferIncomingCall(error, offerSdp) {
  if (error) return console.error("Error generating the offer");
  let response = {
    id: "incomingCallResponse",
    from: from,
    callResponse: "accept",
    sdpOffer: offerSdp
  };
  sendMessage(response);
}

export function register(name) {
  if (name == "") {
    window.alert("You must insert your user name");
    return;
  }
  setRegisterState(REGISTERING);

  let message = {
    id: "register",
    name: name
  };
  sendMessage(message);
}

export function call(peer) {
  if (peer == "") {
    window.alert("You must specify the peer name");
    return;
  }
  setCallState(PROCESSING_CALL);
  let iceservers = {
    iceServers: [
      {
        urls: "stun:192.168.0.15:3478"
      },
      {
        urls: ["turn:192.168.0.15:3478"],
        username: "kurento",
        credential: "kurento"
      }
    ]
  };
  let options = {
    localVideo: videoInput,
    remoteVideo: videoOutput,
    configuration: iceservers,
    onicecandidate: onIceCandidate,
    onerror: onError
  };
  webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendrecv(options, function(
    error
  ) {
    if (error) {
      return error;
    }
    webRtcPeer.generateOffer(onOfferCall);
  });
}

function onOfferCall(error, offerSdp) {
  if (error) return console.error("Error generating the offer");
  console.log("Invoking SDP offer callback function");
  let message = {
    id: "call",
    from: document.getElementById("name").value,
    to: document.getElementById("peer").value,
    sdpOffer: offerSdp
  };
  sendMessage(message);
}

export function stop(message) {
  setCallState(NO_CALL);
  if (webRtcPeer) {
    webRtcPeer.dispose();
    webRtcPeer = null;

    if (!message) {
      let message = {
        id: "stop"
      };
      sendMessage(message);
    }
  }
}

export function onError() {
  setCallState(NO_CALL);
}

function onIceCandidate(candidate) {
  console.log("Local candidate" + JSON.stringify(candidate));

  let message = {
    id: "onIceCandidate",
    candidate: candidate
  };
  sendMessage(message);
}

function sendMessage(message) {
  let jsonMessage = JSON.stringify(message);
  console.log("Senging message: " + jsonMessage);
  ws.send(jsonMessage);
}

export function sendRoomMessage() {
  let message = {
    id: "sendRoomMessage"
  };
  sendMessage(message);
}

/**
 * 获取房间信息
 * @param response
 */
export function getRoomMessage(response) {
  let message = {
    id: "joinRoom",
    name: response.to,
    room: response.roomName
  };
  let accept = false;
  if (response.from === window.localStorage.getItem("username")) {
    accept = true;
  } else {
    accept = window.confirm(
      "User " +
        response.from +
        " is inviting you to join a group call. Do you accept the call?"
    );
  }
  if (accept) {
    window.open(
      "https://192.168.0.15:8443/group-index.html?id=joinRoom&name=" +
        response.to +
        "&room=" +
        response.roomName
    );
  }
}

export function getOnlineUsersRes(response) {
  let contents = [];
  let users = response.users.substring(1, response.users.length-1).split(",");
  console.log(users);
  users.forEach(user => {
    let content = {
      date: "2019.3.26",
      icon: "icon1",
      text: "测试一",
      username: user
    };
    contents.push(content);
  });
  window.localStorage.setItem("users", JSON.stringify(contents));
}

export function getOnlineUsers() {
  let message = {
    id: "getOnlineUsers"
  };
  sendMessage(message);
}
